package com.flyxiaozhu.erp.admin.controllers;

import com.flyxiaozhu.erp.core.entities.SysLog;
import com.flyxiaozhu.erp.core.libs.JSONResult;
import com.flyxiaozhu.erp.core.libs.SearchSpecification;
import com.flyxiaozhu.erp.core.repositories.SysLogRepository;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@RestController
public class SysLogController {
    @Autowired
    SysLogRepository sysLogRepository;

    @Autowired
    HttpServletRequest request;

    @Secured("ROLE_SYSLOG_SELECT")
    @RequestMapping("/sysLog/select")
    public JSONResult getList(@RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "15") Integer size) {
        String createTimeBegin = request.getParameter("search_gte_createTime_dateBegin");
        String createTimeEnd = request.getParameter("search_gte_createTime_dateEnd");

        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, size, sort);
        SearchSpecification<SysLog> specification = new SearchSpecification<>(request);

        specification.setBeforeFilter((list, root, query, cb) -> {
            if (Strings.isNotBlank(createTimeBegin)) {
                list.add(cb.greaterThanOrEqualTo(root.get("createTime"), createTimeBegin));
            }

            if (Strings.isNotBlank(createTimeEnd)) {
                list.add(cb.lessThanOrEqualTo(root.get("createTime"), createTimeEnd));
            }
        });

        Page<SysLog> sysLogPage = sysLogRepository.findAll(specification, pageable);

        return new JSONResult(sysLogPage, pageable.getPageNumber());
    }
}
